package firear.caipiaomonitor;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class LibraryRoomMonitorService extends Service {

    private static final String TAG = "cai";

    public static JSONObject resp = null;
    public static String content = "";
    public static boolean monitoring = false;
    private Notification mNoification = null;
    NotificationManager mNotificationManager;
    private static Thread mMonitorthread;


    public LibraryRoomMonitorService() {
    }

    public static void start(Context ctx){
        Intent intent1 = new Intent(ctx, LibraryRoomMonitorService.class);
        ctx.startService(intent1);
    }
    public static void stop(Context ctx){
        ctx.stopService(new Intent(ctx, LibraryRoomMonitorService.class));
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void makeforceground(){
        String id = "channel1";
        String name = "channel1";
        Intent notifyIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notifyIntent,0);


        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
            Log.i(TAG, mChannel.toString());
            mNotificationManager.createNotificationChannel(mChannel);

            mNoification = new Notification.Builder(this, id).
                    setSmallIcon(R.drawable.icon).
                    setContentTitle("实时彩").
                    setContentText("监听中").
                    setContentIntent(pendingIntent).
                    build();

        }
        // 设置为前台服务,在系统状态栏显示
        startForeground(1, mNoification);


    }
    @Override
    public void onCreate() {

        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        monitoring = true;
        Log.i(TAG, "onCreate");

        //makeforceground();

        mMonitorthread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (monitoring){
                    Log.i(TAG, "checking");
                    get();
                    SystemClock.sleep(10000);
                    if(Thread.interrupted()){
                        Log.i(TAG, "interruped");
                        break;
                    }
                }
                Log.i(TAG, "thread exit");
            }
        });
        mMonitorthread.start();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mMonitorthread.interrupt();
        monitoring = false;

        stopForeground(true);
        Log.i(TAG, "onDestroy");
    }


    public void checkRet(){

        try{
            content = "";
            if(resp != null){
                int code = resp.optInt("errorCode");
                if(code == 0){
                    JSONObject result = resp.optJSONObject("result");
                    JSONObject data = result.optJSONObject("data");
                    String preDrawCode = data.optString("preDrawCode");

                    String[] bitarr = preDrawCode.split(",");
                    CaipiaoInfo info = new CaipiaoInfo();
                    info.time = data.optString("preDrawTime");
                    info.value = preDrawCode;
                    content = info.toString();
                    if(Rule.match(bitarr)){
                        postnotify();
                    }
                }
            }
        }catch ( Exception e){
            e.printStackTrace();
        }
    }


    private void postnotify(){
        String id = "规则提醒";
        String name="规则提醒";
        Notification notification = null;
        Intent notifyIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notifyIntent,0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
            Log.i(TAG, mChannel.toString());
            mNotificationManager.createNotificationChannel(mChannel);

            notification = new Notification.Builder(this)
                    .setChannelId(id)
                    .setContentTitle("规则提醒")
                    .setContentText("符合设置规则了 哈哈!!!")
                    .setDefaults(Notification.DEFAULT_ALL) // 设置用手机默认的震动或声音来提示
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.icon).build();
        }else {
            notification = new Notification.Builder(this)
                    .setContentTitle("规则提醒")
                    .setContentText("符合设置规则了 哈哈!!!")
                    .setDefaults(Notification.DEFAULT_ALL) // 设置用手机默认的震动或声音来提示
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.icon).build();
        }
        mNotificationManager.notify(111123, notification);
    }

    private void get(){
        StringBuilder builder = new StringBuilder();

        try {
            URL url = new URL("https://api.api861861.com/CQShiCai/getBaseCQShiCai.do?issue=11512907&lotCode=10036");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inStrm = httpURLConnection.getInputStream();
                //将响应流转换成字符串
                byte []b=new byte[1024];
                int length=-1;
                while((length=inStrm.read(b))!=-1){
                    builder.append(new String(b,0,length));
                }

                JSONObject json = new JSONObject(builder.toString());
                resp = json;
                checkRet();
                Log.d(TAG,"result============="+builder.toString());
            }



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
